package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import javax.sql.DataSource;

import oracle.net.aso.e;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import pojo.User;

@Repository(value="userdao")
public class UserDaoImpl implements UserDao {
	
	@Autowired
	private DataSource ds;

	@Override
	public User addUser(User u) {
		String sql="insert into um (id,name,age,pwd) values(?,?,?,?)";
		Connection con=null;
		PreparedStatement pst=null;
		try {
			con=ds.getConnection();
			pst=con.prepareStatement(sql);
			pst.setString(1, u.getId());
			pst.setString(2, u.getName());
			pst.setInt(3, u.getAge());
			pst.setString(4, u.getPwd());
			pst.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		}
		close(con, pst, null);		
		return u;
	}

	@Override
	public User findUser(User u) {
		String sql="select * from um where name=? and pwd=?";
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		try {
			con=ds.getConnection();
			pst=con.prepareStatement(sql);
			pst.setString(1, u.getName());
			pst.setString(2, u.getPwd());
			rs=pst.executeQuery();
			if (rs.next()) {
				System.out.println(rs.getString("name"));
				u.setName(rs.getString("name"));
				u.setId(rs.getString("id"));
				u.setPwd(rs.getString("pwd"));
				u.setAge(rs.getInt("age"));
				return u;
			}
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}
		close(con, pst, null);
		return null;
	}
	
	
	public void close (Connection con,PreparedStatement stat,ResultSet rs){
		try {
			if (rs != null) {
				rs.close();

			}
			if (stat != null) {
				stat.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
